# apps/menus/serializers.py
from rest_framework import serializers
from .models import Menu
from apps.users.serializers import UserSimpleSerializer
from ..users.models import QBUser


class MenuSerializer(serializers.ModelSerializer):
    children = serializers.SerializerMethodField()
    roles = UserSimpleSerializer(many=True, read_only=True)
    role_ids = serializers.PrimaryKeyRelatedField(
        queryset=QBUser.objects.all(),
        write_only=True,
        many=True,
        source='roles',
        required=False
    )

    class Meta:
        model = Menu
        fields = [
            'id', 'title', 'name', 'path', 'component', 'icon',
            'menu_type', 'parent', 'order', 'is_active', 'is_external',
            'children', 'roles', 'role_ids'
        ]

    def get_children(self, obj):
        # 递归返回子菜单
        children = obj.children.filter(is_active=True).order_by('order')
        return MenuSerializer(children, many=True).data

    def to_representation(self, instance):
        data = super().to_representation(instance)
        # 如果是按钮，不返回 children
        if instance.menu_type == 'button':
            data.pop('children', None)
        return data